import React, {Component, ComponentClass} from 'react';
import Taro from '@tarojs/taro';
import {View, Input, Picker, Block, Button, Textarea} from '@tarojs/components'
import {AtButton, AtDrawer, AtModal, AtModalHeader, AtIcon, AtModalContent, AtModalAction} from 'taro-ui'
import {http} from '../../utils/http'
import GzhAuth from "../../components/gzh-auth/gzh-auth";
import Confirm from "../components/confirm/confirm";
import NewIcon from '../productForm/components/icon';
import {
  SUPPLIER_PAGE,
  SUPPLIER_DEDRAFTS,
  SUPPLIER_SUBMIT,
  SUPPLIER_PASSANDUNPASS,
  TARO_ENV,
  BASE_URL,
  SYSTEM_UPLOAD,
  SUPPLIER_CONTRACT_SET
} from '../../constants/api'
import {vcmonitor} from "../../utils/tools";
import './index.scss';

type StateProps = {
  listData: any
  drawerShow: boolean
  search: any
  loadMoreStatus: any
  confirmShow: boolean
  confirmTitle: string
  confirmId: any
  confirmCb: any
  active: any
  supplierId: any
  unPassReason: any
  isRefuseOpen: any
}

class productList extends Component {
  state: StateProps = {
    supplierId: null,
    unPassReason: '',
    active: 0,
    confirmTitle: '',
    confirmId: null,
    confirmCb: null,
    confirmShow: false,
    drawerShow: false,
    isRefuseOpen: false,
    loadMoreStatus: 'loading',
    search: {
      page: 1
    },
    listData: []
  }

  setStateSync(state) {
    return new Promise(resolve => {
      this.setState(state, resolve);
    });
  }

  async componentDidShow() {
    vcmonitor(this)
    this.state.search
    const {search} = this.state
    search.page = 1
    await this.setStateSync(search)
    this.reset(0);
  }

  onReachBottom() {
    this.loadMore()
  }

  loadMore() {
    if (this.state.loadMoreStatus != 'noMore') {
      this.setState({loadMoreStatus: 'loading'}, async () => {
        const {search} = this.state;
        search.page++;
        this.setState({
          search
        });
        this.getData(search.page)
      })
    }
  }

  // 关闭筛选
  setDrawer(drawerShow) {
    this.setState({
      drawerShow
    });
  }

  async getData(page?: any, type?: any, status?) {
    let {search, listData} = this.state;
    page = page || 1;
    Taro.showLoading({title: '加载中...'});
    const res = await http.HGet(SUPPLIER_PAGE, {
      ...search,
      type: 'move',
      page,
      status
    });
    if (res.data && res.data.length > 0) {
      if (type == 'reset') {
        listData = res.data;
      } else {
        listData = listData.concat(res.data);
      }
    } else {
      listData = [];
    }
    this.setState({
      listData
    });
    if (res.totalRows <= page * 10) {
      this.setState({
        loadMoreStatus: 'noMore'
      });
    }
    Taro.hideLoading();
  }

  // 搜索
  search(key, value) {
    const search = this.state.search;
    search[key] = value;
    this.setState({
      search
    });
  }

  // 重置
  reset(time: any = 300) {
    const search = this.state.search;
    const search1: any = {};
    search1.page = 1;
    search1.status = search.status;
    this.setState({
      search: search1,
      loadMoreStatus: 'loading'
    });

    setTimeout(() => {
      this.getData(1, 'reset', search.status);
      this.setDrawer(false);
    }, time);
  }

  // 删除
  async delGoods(supplierId) {
    await http.HPost(SUPPLIER_DEDRAFTS, {
      type: 'move',
      supplierId
    });
    this.getData(1, 'reset');
    this.confirmClose();
  }

  // 提交
  async commitGoods(supplierId) {
    const res = await http.postCar(SUPPLIER_SUBMIT, {
      type: 'move',
      supplierId
    });
    if (res) {
      this.confirmClose(false);
      Taro.showToast({title: '提交成功'});
      this.getData(1, 'reset');
    }
  }

  // 提示框点击确定
  async confirmSuccess() {
    const {confirmCb, confirmId} = this.state;
    confirmCb(confirmId);
  }

  // 提示框点击遮罩层隐藏
  confirmClose(isShow = false) {
    this.setState({
      confirmShow: isShow
    });
  }

  // 显示confirm
  confirmOpen(confirmTitle, confirmId, confirmCb) {
    this.setState({
      confirmTitle,
      confirmId,
      confirmCb
    });
    this.confirmClose(true);
  }

  // 类型选择
  cur(active) {
    const {search} = this.state;
    search.status = active == 0 ? '' :
      active == 1 ? '待BDM审核' :
        active == 2 ? '待提交' : '审核完成';
    search.page = 1;
    this.setState({
      active,
      search
    }, () => this.reset());
  }

  // 搜索筛选
  searchScreen() {
    const {active, search} = this.state;
    const types = active == 0 ? '' :
      active == 1 ? '待BDM审核' :
        active == 2 ? '待提交' : '审核完成';
    search.page = 1;
    this.setState({
      search,
      drawerShow: false
    });
    this.getData(0, 'reset', types);
  }

  // 通过
  async adoptGoods(supplierId, op = 'pass', unPassReason, title = '通过成功') {
    this.confirmClose();
    const res = await http.postCar(SUPPLIER_PASSANDUNPASS, {
      type: 'move',
      supplierId,
      op,
      unPassReason
    });
    if (res) {
      Taro.showToast({title, icon: 'none'});
      setTimeout(() => this.reset(), 300);
    }
  }

  // 拒绝
  refuseGoods() {
    const {supplierId, unPassReason} = this.state;
    this.adoptGoods(supplierId, 'unPass', unPassReason, '拒绝成功');
    this.reufseShow();
  }

  // 拒绝原因
  reufseChange(value) {
    this.setState({
      unPassReason: value
    });
  }

  // 拒绝显示
  reufseShow(isShow = false, supplierId?) {
    this.setState({
      isRefuseOpen: isShow,
      supplierId,
      unPassReason: ''
    });
  }

  // 上传文件
  uploadFile(supplierId) {
    const api = BASE_URL + SYSTEM_UPLOAD
    const that = this
    if (TARO_ENV === 'h5') {
      const inp = document.createElement('input');
      try {
        inp.setAttribute('type', 'file');
        inp.accept = '.doc,.docx,.jpg,.jpeg,.png,.gif'
        document.body.appendChild(inp)
        inp.click();
        inp.onchange = (e: any) => {
          const file = e.target.files[0];
          const formData = new FormData();
          formData.set("file", file, file.name);  // 文件对象
          Taro.showToast({
            title: '正在上传...',
            icon: 'loading',
            mask: true,
            duration: 10000
          });
          const xhr = new XMLHttpRequest();
          xhr.open('POST', api, false);
          xhr.setRequestHeader('token', http.getToken());
          xhr.onload = (e: any) => {
            if (e.currentTarget.readyState == 4 && e.currentTarget.status == 200) {
              const data = JSON.parse(e.currentTarget.responseText);
              http.post(SUPPLIER_CONTRACT_SET, {
                file: data.data,
                supplierId
              }).then(res => {
                Taro.showToast({
                  title: '上传成功',
                  mask: true,
                  icon: 'none'
                })
                setTimeout(() => {
                  Taro.hideLoading();
                  document.body.removeChild(inp)
                  this.reset(0);
                }, 1500)
              });
            }
          };
          xhr.send(formData);
        }
      } catch (error) {
        document.body.removeChild(inp)
        Taro.showToast({
          title: '上传失败',
          icon: 'none'
        })
      }
    } else {
      wx.chooseMessageFile({
        count: 1,
        type: "all",
        success(res) {
          // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
          const tempFilePaths = res.tempFiles;
          //启动上传等待中...
          Taro.showToast({
            title: '正在上传...',
            icon: 'loading',
            mask: true,
            duration: 10000
          })
          let uploadImgCount = 0;
          for (let i = 0, h = tempFilePaths.length; i < h; i++) {
            Taro.uploadFile({
              url: api,
              filePath: tempFilePaths[i].path,
              name: 'file',
              formData: {
                'imgIndex': i
              },
              header: http.getHeader(),
              success: function (res) {
                uploadImgCount++;
                const data = JSON.parse(res.data);
                if (res.statusCode == 400) {
                  Taro.showToast({
                    title: data.message,
                    icon: 'none'
                  })
                  return
                }
                Taro.showToast({
                  title: '上传成功',
                  icon: 'none'
                })
                that.reset();
                that.setState({tableFile: data.imageUrl, imgFile: null})
                //如果是最后一张,则隐藏等待中
                if (uploadImgCount == tempFilePaths.length) {
                  setTimeout(() => {
                    Taro.hideToast();
                  }, 2000)
                }
              },
              fail: function () {
                Taro.hideToast();
                Taro.showModal({
                  title: '错误提示',
                  content: '上传文件失败',
                  showCancel: false
                })
              }
            });
          }
        }
      })
    }
  }

  viewContract(contract) {
    const schemeArr = ['.doc', '.docx']
    const flag = schemeArr.some(item => contract.includes(item))
    if (flag) {
      Taro.navigateTo({url: '/main/webview/index?url=' + contract})
    } else {
      Taro.previewImage({urls: [contract]})
    }
  }

  render() {
    const {unPassReason, isRefuseOpen, active, confirmTitle, confirmShow, listData, drawerShow, search} = this.state;
    return (
      <View className='product-business-list'>
        <GzhAuth />
        <View className='product-business-list-ap'>
          <View
            className='product-business-list-ap-item'
            style={active == 0 ? `color:${process.env.mainColor};` : ''}
            onClick={() => this.cur(0)}
          >全部</View>
          <View
            className='product-business-list-ap-item'
            style={active == 1 ? `color:${process.env.mainColor};` : ''}
            onClick={() => this.cur(1)}
          >审核中</View>
          <View
            className='product-business-list-ap-item'
            style={active == 2 ? `color:${process.env.mainColor};` : ''}
            onClick={() => this.cur(2)}
          >待提交</View>
          <View
            className='product-business-list-ap-item'
            style={active == 3 ? `color:${process.env.mainColor};` : ''}
            onClick={() => this.cur(3)}
          >
            已通过
          </View>
          <View>
            <NewIcon
              className='icon iconfont icon-shaixuan-01'
              font='24'
              color='#0bbe7f'
              top='10'
              style='left: -10px;'
              onClick={
                () => {
                  const drawerShow = this.state.drawerShow;
                  this.setState({
                    drawerShow: !drawerShow
                  })
                }
              }
            />
          </View>
        </View>
        <View className='product-business-list-item-wrap'>
          {
            listData && listData.map((item, index) =>
              <View className='product-business-list-item' key={index}>
                <View
                  className='product-business-list-item-right'
                >{item.process_status == null ? '' : item.process_status}</View>
                <View className='product-business-list-item-name'>{item.company}</View>
                <View className='product-business-list-item-content'>
                  创建时间：{item.addDate}
                </View>
                {/* <View className='product-business-list-item-content'>
                  商家地址：{item.address || ''}
                </View> */}
                <View className='product-business-list-item-content'>
                  商家电话：{item.mobile || ''}
                </View>
                {
                  item.refuse_reason && item.process_status == '待提交' &&
                  <View className='product-business-list-item-content'>
                    拒绝原因：{item.refuse_reason}
                  </View>
                }
                {
                  item.add_user && <View className='product-business-list-item-content'>
                    提交人：{item.add_user}
                  </View>
                }
                {
                  item.editorUser && <View className='product-business-list-item-content'>
                    编辑：{item.editorUser}
                  </View>
                }
                <View className='product-business-list-item-btn'>
                  <View className='product-business-list-item-btn-button detail-flex1'>
                    {
                      (item.process_status == '待BDM审核' || item.process_status == '审核完成') &&
                      <View>
                        <AtButton size='small' circle
                          onClick={() => Taro.navigateTo({url: `/main/businessDetail/index?id=${item.id}`})}
                        >详情</AtButton>
                      </View>
                    }
                    <View>
                      {item.contract && <AtButton size='small' circle
                        onClick={() => this.uploadFile(item.id)}
                      >{item.contract ? '修改合同' : '上传合同'}</AtButton>}
                    </View>
                    {item.contract && <View>
                      <AtButton size='small' circle
                        onClick={this.viewContract.bind(this, item.contract)}
                      >查看合同</AtButton>
                    </View>}
                    {(item.process_status == '待提交' && item.isbduser == 1) &&
                      <Block>
                        <View>
                          <AtButton size='small' circle
                            onClick={() => Taro.navigateTo({url: `/main/productForm/business?id=${item.id}`})}
                          >编辑</AtButton>
                        </View>
                        <View>
                          <AtButton size='small' circle
                            onClick={() => this.confirmOpen('确定要提交吗', item.id, this.commitGoods.bind(this))}
                          >提交</AtButton>
                        </View>
                      </Block>
                    }
                    {
                      (item.process_status == '待BDM审核' && item.role == 2) &&
                      <Block>
                        <View>
                          <AtButton size='small' circle
                            onClick={() => this.confirmOpen('确定要通过吗', item.id, this.adoptGoods.bind(this))}
                          >通过</AtButton>
                        </View>
                        <View>
                          <AtButton size='small' circle onClick={() => this.reufseShow(true, item.id)}>拒绝</AtButton>
                        </View>
                      </Block>
                    }
                    {
                      (item.process_status == '待提交' && item.isbduser == 1) &&
                      <View>
                        <AtButton size='small' circle
                          onClick={() => this.confirmOpen('确定要删除吗', item.id, this.delGoods.bind(this))}
                        >删除</AtButton>
                      </View>
                    }
                  </View>
                </View>
              </View>)
          }
          {
            listData.length <= 0 && <View className='center'>暂无数据信息</View>
          }
        </View>
        <View
          className={process.env.TARO_ENV === 'h5' ? "addInfo h5-small" : "addInfo"}
          style={`background-color: ${process.env.mainColor}`}
          onClick={() => Taro.navigateTo({url: `/main/productForm/business`})}
        >
          增加商家信息 +
        </View>
        <AtDrawer
          show={drawerShow}
          mask
          onClose={this.setDrawer.bind(this, false)}
          right
          width='70%'
        >
          <View className='scrrent'>
            <View className='scrrent-item'>商家名称</View>
            <View className='scrrent-item scrrent-item-font-small scrrent-item-border'>
              <Input
                placeholder='请输入商家名称'
                onInput={({detail: {value}}) => this.search("search_company", value)}
                value={search.search_company}
              />
            </View>
            <View className='scrrent-item'>商家电话</View>
            <View className='scrrent-item scrrent-item-font-small scrrent-item-border'>
              <Input
                placeholder='请输入商家电话'
                onInput={({detail: {value}}) => this.search("search_mobile", value)}
                value={search.search_mobile}
              />
            </View>
            <View className='scrrent-item'>创建日期起</View>
            <View className='scrrent-item scrrent-item-font-small scrrent-item-border'>
              <Picker mode='date' onChange={({detail: {value}}) => this.search('search_add_Date_start', value)}
                value={search.search_add_Date_start}
              >
                {search.search_add_Date_start || "请选择创建日期"}
              </Picker>
            </View>
            <View className='scrrent-item'>创建日期止</View>
            <View className='scrrent-item scrrent-item-font-small scrrent-item-border'>
              <Picker mode='date' onChange={({detail: {value}}) => this.search('search_add_Date_end', value)}
                value={search.search_add_Date_end}
              >
                {search.search_add_Date_end || "请选择创建日期"}
              </Picker>
            </View>
            <View className='scrrent-item detail-flex detail-flex-fixed'>
              <View className='scrrent-item-btn' onClick={() => this.reset()}>
                重置
              </View>
              <View
                className='scrrent-item-btn'
                style={`background-color: ${process.env.mainColor}; color: #fff;`}
                onClick={() => this.searchScreen()}
              >
                搜索
              </View>
            </View>
          </View>
        </AtDrawer>
        {confirmShow &&
          <View style='width: 100%; height: 100%; position:fixed; left: 0; top: 0; z-index: 1;' onClick={(e) => {
            e.stopPropagation();
          }}
          >
            <Confirm
              width='70'
              content={confirmTitle}
              success={() => this.confirmSuccess()}
              cancel={() => this.confirmClose()}
              close={() => this.confirmClose()}
            />
          </View>
        }
        {isRefuseOpen && <AtModal className='model' isOpened={isRefuseOpen}>
          <AtModalHeader>拒绝原因<AtIcon onClick={() => {
            this.setState({isRefuseOpen: false})
          }} className='close-cla' value='close' size='20' color='#888888'
          /></AtModalHeader>
          <AtModalContent>
            <Textarea
              maxLength={100}
              placeholder='请输入拒绝原因'
              placeholderStyle='color: #c5c5c5;'
              style={`width: 99%; height: 100px; border: solid 1px #c5c5c5; box-sizing: border-box; padding: 10px; ${unPassReason == '' ? 'color: #c5c5c5;' : 'color: #000'}`}
              value={unPassReason}
              onInput={({detail: {value}}) => this.reufseChange(value)}
            />
          </AtModalContent>
          <AtModalAction>
            <Button
              className='readed'
              onClick={() => this.refuseGoods()}
              style={`background: ${process.env.mainColor}; color: #fff;`}
            >确定</Button>
          </AtModalAction>
        </AtModal>}
      </View>
    )
  }
}

export default productList as ComponentClass;
